<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<div class="page">
				<div class="page-left">
					<el-scrollbar>
						<el-tree
							ref="treeRef"
							:data="treeList"
							:props="defaultProps"
							default-expand-all
							:expand-on-click-node="false"
							node-key="id"
							:highlight-current="true"
							:current-node-key="currentNodeKey"
							@node-click="handleNodeClick"
						/>
					</el-scrollbar>
					<div class="page-btn">
						<el-button type="primary" class="full-screen" icon="FullScreen" @click="setFullScreen">组态全屏</el-button>
						<el-button type="primary"  class="rule-btn" icon="View" @click="viewMeta">查看规则</el-button>
					</div>
				</div>
				
				
				<div class="page-right">
					
					<met2d-view id="container" :meta2dUrl="tagJson" :met2dId="met2dId" ref="tagLabel"></met2d-view>
				</div>
				<!-- 乐吾乐组态弹窗 -->
				<custom-dialog ref="sbxxDialog" :width="dialogWidth" :title="dialogTitle" :needModal="needModal">
					<template v-slot:content>
						<div class="table-content" style="min-height: 500px">
							<div>
								<!-- 实时信息 -->
								<div class="d-title">仪表信息</div>
								<div class="info">
									<el-row class="row-text">
										<el-col :span="8">
											<div class="label">仪表名称:</div>
											<div class="value">{{ dialogObj.deviceName }}</div>
										</el-col>
										<el-col :span="8">
											<div class="label">备注:</div>
											<div class="value">{{ dialogObj.remark }}</div>
										</el-col>
									</el-row>
								</div>
								<div class="d-title">实时信息</div>
								<div class="info">
									<div class="row-container">
										<div class="row-item" v-for="(item, index) in dialogObj.properties" :key="index">
											<div class="label">{{ item.name }}:</div>
											<div class="value">{{ item.value }} {{ item.unit }}</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</template>
				</custom-dialog>
				<el-dialog v-model="centerDialogVisible" draggable title="监控视频" width="60%" center :before-close="handleClose">
					<!-- 内容区域 -->
					<el-container style="margin-left: 5px">
						<el-main style="padding: 0">
							<div style="width: 99%; height: 65vh; display: flex; flex-wrap: wrap; background-color: #000" v-if="videoUrl != ''">
								<player-video ref="player" :videoUrl="videoUrl" :_uid="'vidoe'" :isShow="true" fluent autoplay />
							</div>
							<div class="zanwu_data" v-else>暂无视频数据</div>
						</el-main>
						<!-- <el-aside width="3vh" class="viodeheader">
						分屏
						<el-icon class="btn" :class="{ active: spilt == 1 }" @click="spilt = 1"><FullScreen /></el-icon>
						<el-icon class="btn" :class="{ active: spilt == 4 }" @click="spilt = 4"><Menu /></el-icon>
						<el-icon class="btn" :class="{ active: spilt == 9 }" @click="spilt = 9"><Grid /></el-icon>
					</el-aside> -->
					</el-container>
					<!-- 底部菜单 -->
					<!-- <template #footer>
					<div class="dialog-footer">
						<el-button @click="centerDialogVisible = false">Cancel</el-button>
						<el-button type="primary" @click="centerDialogVisible = false"> Confirm </el-button>
					</div>
				</template> -->
				</el-dialog>
				<!-- 热泵主机弹窗 -->
				<el-dialog v-model="RSBVisible" draggable :title="devTitle" width="50%" center>
					<!-- 内容区域 -->
					<el-container style="margin-left: 5px">
						<el-tabs v-model="activeName" class="demo-tabs" @tab-click="">
							<el-tab-pane label="基本信息" name="first">
								<el-row>
									<el-col :span="12" v-for="(item, index) in devPropertyData" :key="index" style="height: 40px; line-height: 40px">
										<div style="display: flex; justify-content: space-between">
											<div style="margin-left: 20px">{{ item.name }}:</div>
											<div style="margin-right: 30px" v-if="item.dataType.type == 'enum' || item.dataType.type == 'bool'">
												{{ item.dataType.specs[item.value] }}
												<el-icon
													style="font-size: 18px"
													v-if="(item.name.includes('运行模式') || item.name.includes('定时开关')) && ms_flag == '1'"
													@click="showInvokeService(item)"
													><CaretBottom
												/></el-icon>
											</div>
											<div style="margin-right: 30px" v-else>{{ item.value }}{{ item.unit }}</div>
										</div>
									</el-col>
								</el-row>
							</el-tab-pane>
							<el-tab-pane label="定时设置" name="second">
								<el-row>
									<el-col :span="12" v-for="(item, index) in timerList" :key="index" style="height: 40px; line-height: 40px">
										<div style="display: flex; justify-content: space-between">
											<div style="margin-left: 20px">{{ item.name }}:</div>
											<div style="margin-right: 30px">
												{{ item.value }}{{ item.unit
												}}<el-icon style="font-size: 18px" v-if="ms_flag == '1'" @click="showInvokeService(item)"><CaretBottom /></el-icon>
											</div>
										</div>
									</el-col>
								</el-row>
							</el-tab-pane>
							<el-tab-pane label="故障详情" name="third">
								<el-row>
									<el-col :span="12" v-for="(item, index) in faultData" :key="index" style="height: 40px; line-height: 40px">
										<div style="display: flex; justify-content: space-between">
											<div style="margin-left: 20px">{{ item.name }}:</div>
											<div style="margin-right: 30px" v-if="item.value == 0">
												<img style="width: 30px; height: 30px" alt="" src="/@/assets/warn_gray.png" />
											</div>
											<div style="margin-right: 30px" v-else><img style="width: 30px; height: 30px" alt="" src="/@/assets/warn_red.png" /></div>
										</div>
									</el-col>
								</el-row>
								<el-row>
									<div v-if="ms_flag == '1'" style="width: 100%; display: flex; justify-content: center; margin-top: 20px">
										<el-button plain style="width: 98%" @click="clearFault()">清除故障</el-button>
									</div>
								</el-row>
							</el-tab-pane>
						</el-tabs>
					</el-container>
					<!-- 底部菜单 -->
					<!-- <template #footer>
						<div class="dialog-footer">
							<el-button @click="RSBVisible = false">取消</el-button>
							<el-button type="primary" @click="RSBVisible = false">确认</el-button>
						</div>
					</template> -->
				</el-dialog>
				<el-dialog
					:title="state.title"
					v-model="state.serviceFormVisible"
					width="40%"
					@close="closeDialog"
					:close-on-press-escape="false"
					:close-on-click-modal="false"
					append-to-body
					destroy-on-close
				>
					<el-form v-if="state.serviceFormVisible" label-width="250px" :model="state.serviceForm" ref="serviceForm">
						<div>
							<el-input v-model="state.serviceForm.identifier" type="hidden" />
						</div>

						<el-form-item :label="state.serviceForm.params.name + ':'">
							<el-select style="width: 70%" v-model="state.serviceForm.params.value" v-if="state.serviceForm.params.name.includes('小时')">
								<el-option v-for="item in 24" :key="item" :label="item" :value="item" />
							</el-select>
							<el-select style="width: 70%" v-model="state.serviceForm.params.value" v-else-if="state.serviceForm.params.name.includes('分钟')">
								<el-option v-for="item in 59" :key="item" :label="item" :value="item" />
							</el-select>
							<el-radio-group v-model="state.serviceForm.params.value" v-else>
								<el-radio v-for="(value, key, index) in state.serviceForm.params.dataType?.specs" :key="index" :label="key" :value="key">{{
									value
								}}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-form>
					<template #footer>
						<div class="dialog-footer">
							<el-button @click="closeDialog">取消</el-button>
							<el-button type="primary" :loading="state.loading" class="title" @click="submitServiceForm">确认</el-button>
						</div>
					</template>
				</el-dialog>
				<!-- 规则弹框 -->
				 <rule-dialog ref="rulebox"></rule-dialog>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { sceneObjQuery, sceneObjQuery2, zutaiDevinfo, getDevice } from '/@/api/basiciot/iconfiguration/list';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';
import mittBus from '/@/utils/mitt';
import { getObj, serviceInvoke } from '/@/api/basiciot/device/device';
import moment from 'moment';
import { validateNull } from '/@/utils/validate';


// 引入组件
const Met2dView = defineAsyncComponent(() => import('./met2d.vue'));
const ruleDialog = defineAsyncComponent(() => import('./rule/rule.vue'));

const CustomDialog = defineAsyncComponent(() => import('/@/components/customDialog/custom-dialog.vue'));
const playerVideo = defineAsyncComponent(() => import('/@/components/VideoPlayer/index.vue'));

const sbxxDialog: any = ref();
const rulebox: any = ref();

const stores = useTagsViewRoutes();

const timerList = ref([]);
const timerProperty = ['T40055_LSB', 'T40056_MSB', 'T40056_LSB', 'T40057_MSB', 'T40057_LSB', 'T40058_MSB', 'T40058_LSB', 'T40059_MSB'];
const ms_flag = ref();
const RSBVisible = ref(false);
const devTitle = ref('');
const activeName = ref('first');
const devProperty = [
	'T40012_LSB',
	'T40040_LSB',
	'T40050_Bit9',
	'T40042_MSB',
	'T40050_Bit0',
	'T40042_LSB',
	'T40028_Bit15',
	'T40116',
	'T40012_Bit13',
	'T40117',
	'T40002_MSB',
	'T40011_Bit0',
	'T40013_MSB',
	'T40119',
	'T40002_LSB',
	'T40120',
	'T40036_MSB',
	'T40121',
	'T40036_LSB',
	'T40051_Bit3_bit0',
	'T40040_MSB',
	'T40050_Bit12',
	'T40050_Bit13',
];
const faultId = [
	'T40014_Bit15',
	'T40014_Bit8',
	'T40014_Bit14',
	'T40014_Bit4',
	'T40014_Bit13',
	'T40014_Bit3',
	'T40014_Bit12',
	'T40014_Bit2',
	'T40014_Bit11',
	'T40014_Bit1',
	'T40014_Bit10',
	'T40014_Bit0',
	'T40014_Bit9',
];
const devUnitNo = ref('');
const state = reactive({
	title: '',
	serviceFormVisible: false,
	serviceForm: {
		identifier: '',
		params: {
			name: '',
			value: '',
			dataType: {},
		},
	},
});

const devPropertyData = ref([]);
const faultData = ref([]);
const showViewBtn = ref(false)
let tagId = ref('');
let tagJson = ref('');

let tagLabel = ref();
let met2dId = ref('');

let treeList = ref([]);
let currentNodeKey = ref('');
const treeRef = ref();
const centerDialogVisible = ref(false);
const defaultProps = {
	children: 'children',
	label: 'name',
	value: 'id',
};

let dialogObj: any = reactive({
	deviceName: '',
	remark: '',
});

let dialogWidth = ref(900);
let dialogTitle = ref('电表详情');
let needModal = ref(false);

//视频 spilt: 1, //分屏
let spilt = ref('1');
let videoUrl = ref('');
const showInvokeService = (service) => {
	state.serviceFormVisible = true;
	state.title = '服务调用';
	state.serviceForm.identifier = service.identifier;
	state.serviceForm.params = {
		name: service.name,
		value: service.value.toString(),
		dataType: service.dataType,
	};
};

const viewMeta = () => {
	if(!validateNull(met2dId.value)){
		rulebox.value.show(met2dId.value);
	}
	
}

const closeDialog = () => {
	state.serviceFormVisible = false;
};
const submitServiceForm = () => {
	let params = {
		unitNo: devUnitNo.value,
		timestamp: moment().valueOf(),
	};
	if (state.serviceForm.identifier == 'T40050_Bit9') {
		//运行模式
		params.service = 'Set_40050_Bit9';
		params.args = {
			mode: state.serviceForm.params.value,
		};
	} else if (state.serviceForm.identifier == 'T40050_Bit12') {
		//定时开关1
		params.service = 'Set_Timer_Enable';
		params.args = {
			timer_sn: '1',
			iEnable: state.serviceForm.params.value,
		};
	} else if (state.serviceForm.identifier == 'T40050_Bit13') {
		//定时开关2
		params.service = 'Set_Timer_Enable';
		params.args = {
			timer_sn: '2',
			iEnable: state.serviceForm.params.value,
		};
	} else if (state.serviceForm.identifier == 'T40055_LSB') {
		//定时1开机小时
		params.service = 'Set_onoff_timer_hour';
		params.args = {
			timer_sn: '1',
			onoff: '1',
			hour: state.serviceForm.params.value,
		};
	} else if (state.serviceForm.identifier == 'T40056_MSB') {
		//定时1开机分钟
		params.service = 'Set_onoff_timer_minute';
		params.args = {
			timer_sn: '1',
			onoff: '1',
			minute: state.serviceForm.params.value,
		};
	} else if (state.serviceForm.identifier == 'T40056_LSB') {
		//定时1关机小时
		params.service = 'Set_onoff_timer_hour';
		params.args = {
			timer_sn: '1',
			onoff: '0',
			hour: state.serviceForm.params.value,
		};
	} else if (state.serviceForm.identifier == 'T40057_MSB') {
		//定时1关机分钟
		params.service = 'Set_onoff_timer_minute';
		params.args = {
			timer_sn: '1',
			onoff: '0',
			minute: state.serviceForm.params.value,
		};
	} else if (state.serviceForm.identifier == 'T40057_LSB') {
		//定时2开机小时
		params.service = 'Set_onoff_timer_hour';
		params.args = {
			timer_sn: '2',
			onoff: '1',
			hour: state.serviceForm.params.value,
		};
	} else if (state.serviceForm.identifier == 'T40058_MSB') {
		//定时2开机分钟
		params.service = 'Set_onoff_timer_minute';
		params.args = {
			timer_sn: '2',
			onoff: '1',
			minute: state.serviceForm.params.value,
		};
	} else if (state.serviceForm.identifier == 'T40058_LSB') {
		//定时2关机小时
		params.service = 'Set_onoff_timer_hour';
		params.args = {
			timer_sn: '2',
			onoff: '0',
			hour: state.serviceForm.params.value,
		};
	} else if (state.serviceForm.identifier == 'T40059_MSB') {
		//定时2关机分钟
		params.service = 'Set_onoff_timer_minute';
		params.args = {
			timer_sn: '2',
			onoff: '0',
			minute: state.serviceForm.params.value,
		};
	}
	serviceInvoke(params).then((res) => {
		if (res.ok) {
			state.serviceFormVisible = false;
			useMessage().success('操作成功');
			getDetailRSBInfo(devUnitNo.value);
		} else {
			useMessage().error(err.msg);
		}
	});
};
const clearFault = async () => {
	try {
		await useMessageBox().confirm('是否确认清除故障？');
	} catch {
		return;
	}
	serviceInvoke({
		unitNo: devUnitNo.value,
		service: 'Set_40051_Bit9',
		args: {},
		timestamp: moment().valueOf(),
	}).then((res) => {
		if (res.ok) {
			useMessage().success('操作成功');
			getDetailRSBInfo(devUnitNo.value);
		} else {
			useMessage().error(err.msg);
		}
	});
};

const timer = ref(0);
watch(RSBVisible, (value) => {
	//监听RSBVisible的变化 隔两秒 刷新数据
	// if (value) {
	// 	timer.value = setInterval(() => {
	// 		getDetailRSBInfo(devUnitNo.value);
	// 	}, 2000);
	// } else {
	// 	clearInterval(timer.value);
	// }
});
// 页面加载时
onMounted(() => {
	getTreeList();

	nextTick(() => {
		mittBus.on('openShowStatusDb', (params: any) => {
			sbxxDialog.value.openDialog();
			getDetailInfo(params.unitNo);
			if (params.msgType == 'SHOWSTATUSDB') {
				dialogTitle.value = '电表详情';
			} else {
				dialogTitle.value = '水表详情';
			}
		});
		mittBus.on('openShowVideo', (params: any) => {
			let obj = {
				ipAdress: params.dataObj.params.ipAdress,
				ipPort: params.dataObj.params.ipPort,
				username: params.dataObj.params.username,
				password: params.dataObj.params.password,
				type: params.dataObj.params.type,
				channel: params.dataObj.params.channel,
				ml: params.dataObj.params.ml,
			};
			centerDialogVisible.value = true;
			getDevice(obj).then((res) => {
				if (res.code == 0) {
					videoUrl.value = res.data.ws;
				} else {
					videoUrl.value = '';
				}
			});
		});
		mittBus.on('openShowStatusRSB', (params: any) => {
			RSBVisible.value = true;
			activeName.value = 'first';
			ms_flag.value = params.MS_flag;
			getDetailRSBInfo(params.unit_no);
		});
	});
});
const getDetailRSBInfo = (unitNo: string | undefined) => {
	devTitle.value = '';
	devUnitNo.value = unitNo;
	devPropertyData.value = [];
	faultData.value = [];
	timerList.value = [];
	getObj(unitNo).then((res) => {
		devTitle.value = res.data.deviceName;
		for (let i = 0; i < devProperty.length; i++) {
			devPropertyData.value.push(res.data.properties?.find((item) => item.identifier == devProperty[i]));
		}
		for (let i = 0; i < faultId.length; i++) {
			faultData.value.push(res.data.properties?.find((item) => item.identifier == faultId[i]));
		}
		for (let i = 0; i < timerProperty.length; i++) {
			timerList.value.push(res.data.properties?.find((item) => item.identifier == timerProperty[i]));
		}
	});
};
const getTreeList = () => {
	sceneObjQuery().then((res) => {
		treeList.value = res.data || [];
		let id = res.data[0]?.id;
		currentNodeKey.value = id;
		treeRef.value.setCurrentKey(id);
	});
};

const handleNodeClick = (data: any) => {
	currentNodeKey.value = data.id;
	treeRef.value.setCurrentKey(data.id);
	tagId.value = data.id;
	tagJson.value = data.json;
	met2dId.value = data.scadaId;
	showViewBtn.value = true
};

const getDetailInfo = (unitNo: string | undefined) => {
	zutaiDevinfo(unitNo).then((res) => {
		let data = res.data;
		dialogObj.deviceName = data.deviceName;
		dialogObj.properties = data.properties;
		dialogObj.remark = data.remark;
	});
};
const handleClose = (done: () => void) => {
	videoUrl.value = '';
	done();
};

const setFullScreen = () => {
	document.getElementById('container').requestFullscreen();
	tagLabel.value.resize();
};

// 页面销毁时，关闭监听布局配置/i18n监听
onUnmounted(() => {
	mittBus.off('openShowStatusDb');
	mittBus.off('openShowVideo');
});
</script>

<style lang="scss" scoped>
.demo-tabs {
	width: 100%;
	height: 550px;
}
.page {
	position: relative;
	display: flex;
	.page-left {
		height: 400px;
		width: 150px;
		.el-tree {
			width: 150px;
			border-radius: 5px;
		}
	}
	.page-right {
		position: relative;
		flex: 1;
	}
}
.zanwu_data {
	height: 300px;
	line-height: 300px;
	text-align: center;
	margin-left: -40px;
}
.full-screen {
	// position: absolute;
	// right: 0;
	// cursor: pointer;
	// z-index: 100;
	// background: rgba(0, 0, 0, 0.5);
	// color: #fff;
	// &:hover {
	// 	transform: scale(1.2);
	// }
}
.rule-btn {
	// position: absolute;
	// left: 10px;
	// top: 10px;
	// z-index: 100;
}
.page-btn {
	position: absolute;
	bottom: 0;
	width: 150px;
	.el-button {
		margin-bottom: 10px;
		margin-left: 0;
	}
}
</style>
